package com.lq.schoolshop.controller.before;

import com.lq.schoolshop.bean.Result;
import com.lq.schoolshop.bean.StatusCode;
import com.lq.schoolshop.controller.BaseController;
import com.lq.schoolshop.dao.OrderMapper;
import com.lq.schoolshop.model.PayModel;
import com.lq.schoolshop.pojo.Expand.ShopAndGoods;
import com.lq.schoolshop.pojo.Expand.ShopAndGoodsVO;
import com.lq.schoolshop.pojo.Expand.UserExamp;
import com.lq.schoolshop.pojo.PayReciveModel;
import com.lq.schoolshop.service.SendOrderService;
import com.lq.schoolshop.service.ShopCarService;
import com.lq.schoolshop.service.UserService;
import com.lq.schoolshop.service.impl.RemotePayClientImpl;
import com.lq.schoolshop.util.PayUtil;
import com.lq.schoolshop.util.RabbitMQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author
 * @Date2021/1/13 21:33
 * @Version V1.0
 * 支付模块
 **/
@Api(value = "商城前台功能--支付模块",tags = "商城前台功能--支付模块")
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping("pay")
@Controller
public class ForPaymentController extends BaseController {

    @Autowired
    private SendOrderService sendOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShopCarService shopCarService;

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @ApiOperation(value = "获取需要支付的物品",notes = "获取需要支付的物品的数量价格信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "购物车ID",dataType = "String[]",required = true,paramType = "query"),
            @ApiImplicitParam(name = "pay_type",value = "支付方式",dataType = "String",required = true,paramType = "query"),
    })
    @ResponseBody
    @RequestMapping(value = "/pay",method = RequestMethod.POST)
    public Map<String, Object>  pay(@RequestHeader("define-token") String language,@RequestParam("id") String[]id,@RequestParam("pay_type")int pay_type){
        //判断该购物车ID 是否存在该用户的相对应的购物车下面  如果是 就提交 如果不是就给予错误提示  防止用户非法进行更改数据
        int userint = getUserIDByToken(language);
        StringBuilder sb = new StringBuilder();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> remoteMap = new HashMap<String, Object>();
        DecimalFormat decimalFormat = new DecimalFormat("##0.00");
        String extra = userint+"";
        if (id.length <= 0) {
            resultMap.put("code",200);
            resultMap.put("msg","失败");
        } else {
            int[] intnum = new int[id.length];
            for (int i = 0; i < id.length; i++) {
                intnum[i] = Integer.parseInt(id[i]);
            }

            List<ShopAndGoods> shopAndGoods = shopCarService.selByShopId(intnum);

            double money = sendOrderService.selSumByShopID(intnum);  //根据购物车ID 查询总价
            System.out.println(money);


            for (ShopAndGoods shopAndGood : shopAndGoods) {
                sb.append(shopAndGood.getId());
                sb.append("-");
            }
            String price = decimalFormat.format(money);
            remoteMap.put("money", price);
            remoteMap.put("pay_type", pay_type);
            remoteMap.put("order_no", PayUtil.getOrderIdByUUId());
            remoteMap.put("subject", sb.toString());
            remoteMap.put("app_id", PayUtil.APP_ID);
            remoteMap.put("extra", extra);
            remoteMap.put("sign", PayUtil.getSign(remoteMap));

            resultMap.put("flag",true);
            resultMap.put("code",200);
            resultMap.put("msg","成功");
            resultMap.put("data", PayUtil.payOrder(remoteMap));
        }
        return resultMap;
    }


    @ApiOperation(value = "后台支付业务处理",notes = "支付业务处理")
    @Transactional
    @RequestMapping("/notifyPay")
    @ResponseBody
    public String notifyPay(HttpServletRequest request, HttpServletResponse response,PayModel payModel) {
        //支付宝=43 微信支付=44
        String payType="";
        //是否篡改了数据
        String fanfa="";
        // 保证密钥一致性
        if (PayUtil.checkSign(payModel)) {
            // TODO 支付成功的业务处理
            String pay_type = payModel.getPay_type();  //支付方式
            String subject = payModel.getSubject();     //购物车ID
            String[] split = subject.split("-");   //购物车ID
            String sendmoney = payModel.getMoney();   //用户金额
            String extra = payModel.getExtra();   //用户ID
            int useridint = Integer.parseInt(extra);
           // double snedmoneyint = Integer.parseInt(sendmoney); //用户金额 转成int
            double snedmoneyint = Double.parseDouble(sendmoney);

            //1.根据用户ID 查询用户信息
            UserExamp showall = userService.showall(useridint);

            if(split.length<=0){
                System.out.println("传过来的商品ID为NULL");
            }else {
                int[] intnum = new int[split.length];
                for (int i = 0; i < split.length; i++) {
                    intnum[i] = Integer.parseInt(split[i]);
                    System.out.println("接到的购物车:"+intnum[i]);
                }

                double money = sendOrderService.selSumByShopID(intnum);    //根据购物车ID 查询总价

                //2.验证金额传来的金额是否跟数据库查出来的一致
                if(pay_type.equals("43")){
                    payType = "支付宝";
                    if(money-snedmoneyint<=0.1){
                        //如果实际金额和支付金额 之差 小于或者等于0.1  则给予通过
                        fanfa="成功";
                    }else{
                        //金额之差太大 可能金额被篡改 不给与通过 吞钱处理。
                        fanfa="非法金融攻击";
                    }
                }else {
                    payType = "微信";
                    if(money-snedmoneyint<=0.1){
                        //如果实际金额和支付金额 之差 小于或者等于0.1  则给予通过
                        fanfa="成功";
                    }else {
                        //金额之差太大 可能金额被篡改 不给与通过 吞钱处理。
                        fanfa="非法金融攻击";
                    }
                }//金额验证

                //1.根据购物车ID 查询到购物车信息和商品信息
                List<ShopAndGoods> shopAndGoods = shopCarService.selByShopId(intnum);

                //2.插入订单表
                orderMapper.insertOrderAll(payModel.getOrder_no(),useridint,money,showall.getAddress(),showall.getPhone(),payType,fanfa+payModel.getResult(),"待发货");

                //4.更新详情表信息
                for (ShopAndGoods shopAndGood : shopAndGoods) {
                    orderMapper.insertOrderDetailAll(payModel.getOrder_no(),shopAndGood.getGid(),shopAndGood.getCount(),shopAndGood.getGprice()*shopAndGood.getCount());
                    //5.更新商品销量 和库存
                    orderMapper.updateGoodsSellCount(shopAndGood.getCount(),shopAndGood.getCount(),shopAndGood.getGid());
                }

                //5.删除用户对应的购物车商品
                shopCarService.deleteorderByAll(intnum);
                /***************************消息队列发送消息*********************************/
                Connection connection = RabbitMQUtils.getConnection();
                Channel channel = null;
                try {
                    channel = connection.createChannel();
                    channel.queueDeclare("static",true,false,false,null);
                    channel.basicPublish("","static",null,"1".getBytes());
                    RabbitMQUtils.closeConnectionAndChanel(channel,connection);
                } catch (IOException e) {
                    RabbitMQUtils.closeConnectionAndChanel(channel,connection);
                    e.printStackTrace();
                }
                System.out.println("发送消息到队列");
                /***************************消息队列发送消息*********************************/

            }//传过来的商品是否为空

            System.out.println("支付成功");
            return "success";
            //response.getWriter().println("success");
        } else {
            // 签名错误
            System.out.println("签名错误");
            return "签名错误";
            //response.getWriter().println("签名错误");

        }//支付是否成功

    }

    @ApiOperation(value = "后台支付最终返回",notes = "后台支付最终返回")
    @ResponseBody
    @RequestMapping(value = "/returnPay",method = RequestMethod.GET)
    public String returnPay(HttpServletRequest request, HttpServletResponse response, PayModel payModel) {
        // 保证密钥一致性
        if (PayUtil.checkSign(payModel)) {
            // 建议本面仅显示支付结果,支付成功的业务处理放在如上的notifyPay里
            System.out.println("支付成功,订单号:" + payModel.getOrder_no());
        } else {
            // 签名错误
            System.out.println("签名错误");
        }
        return "成功";
    }

    @ApiOperation(value = "支付測試接口",notes = "支付測試")
    @ResponseBody
    @RequestMapping(value = "/paytest",method = RequestMethod.GET)
    public String paytest(){
        return "我是支付測試接口";
    }





}
